<template>
  <div class="zs-table-page-container">
    <div class="zs-card-sm zs-space-bottom zs-layout-flex-row zs-layout-justify-between">
      <span>
        <el-select @change="queryList" v-model="queryParams.biProjectCode" filterable clearable
          class="zs-select-md zs-space-right-sm" placeholder="项目名称">
          <el-option v-for="item in projectList" :key="item.biProjectCode" :label="item.biProjectName"
            :value="item.biProjectCode" />
        </el-select>
        <el-select @change="queryList" v-model="queryParams.formatCode" class="zs-select-md zs-space-right-sm"
          placeholder="业态" clearable>
          <el-option v-for="item in dictObj.PROJECT_COMMERCIAL_ACTIVITIES" :key="item.id" :label="item.dictLabel"
            :value="item.dictValue" />
        </el-select>
        <el-cascader placeholder="城市" @change="queryList" :teleported="false" :show-all-levels="false" ref="cascaderRef"
          v-model="queryParams.cityId" :options="citys" :props="cascaderProp" clearable
          class="zs-select-md zs-space-right-sm" />
        <el-popover popper-class="zs-popper" placement="bottom-end" trigger="click">
          <template #reference>
            <el-button class="zs-btn-square-solid"
              :class="{ 'zs-btn-square-solid-active': queryParams.groupCode || queryParams.yearmonth }">
              <el-icon>
                <MoreFilled />
              </el-icon>
            </el-button>
          </template>
          <template #default>
            <el-select  @change="queryList" v-model="queryParams.groupCode" filterable clearable class="zs-select-md zs-space-right-sm"
              placeholder="集团">
              <el-option v-for="item in dictObj.INVESTOR" :key="item.dictValue" :label="item.dictLabel"
                :value="item.dictValue" />
            </el-select>
            <el-date-picker @change="queryList" class="zs-space-right-sm" v-model="queryParams.yearmonth" type="month"
              placeholder="月份" :clearable="false" value-format="YYYY-MM" />
            <!-- <div class="popover-container"> -->

              <!-- <div class="cur-picker-container"> -->
                <!-- <el-date-picker
                  style="width:100%"
                  :teleported="false"
                  v-model="queryParams.yearmonth"
                  type="monthrange"
                  range-separator="~"
                  start-placeholder="开始月"
                  end-placeholder="结束月"
                  value-format="YYYY-MM"
                  :disabledDate="timeDisabled"
                /> -->
              <!-- </div> -->
            <!-- </div> -->
              <!-- @change="" -->
            <!-- <el-date-picker @change="queryList" class="zs-space-right-sm" v-model="queryParams.yearmonth" type="month"
              placeholder="月份" :clearable="false" value-format="YYYY-MM" /> -->
          </template>
        </el-popover>
        <el-button @click="queryList" class="zs-btn-plain">查询</el-button>
      </span>
      <span class="zs-layout-flex-row">
        <el-button
          :class="{ 'zs-btn-plain': curCardDataType == 'echarts', 'zs-btn-primary': curCardDataType == 'list' }"
          @click="handleSwitch('list')">表格</el-button>
        <el-button
          :class="{ 'zs-btn-plain': curCardDataType == 'list', 'zs-btn-primary': curCardDataType == 'echarts' }"
          @click="handleSwitch('echarts')">图形</el-button>
        <el-button class="zs-btn-plain" @click="handleDownload"><el-icon class="el-icon--left">
          <Upload /> 
          </el-icon>导出</el-button>
      </span>
    </div>
    <div class="zs-card zs-table-page-content">
      <hsPageTable indexFixed v-if="curCardDataType == 'list'" :loading="tableData.loading" :total="tableData.total" :headerCellClass="tableData.headerCellClassFn"
        :tableData="tableData.data" @pageChange="pageChange" :cellClassName="tableData.cellClassFn">
        <template #column>
          <el-table-column
            v-for="item in tableData.columns"
            :key="item.prop"
            v-bind="item"
            :show-overflow-tooltip="!item.isNotooltip"
          >
          <template #default="scope">
            <template v-if="item.render">
              <hsTableRender :render="item.render(scope)"></hsTableRender>
            </template>
            <template v-else-if="item.headers">
              <el-table-column v-for="headerItem in item.headers" :key="headerItem" v-bind="headerItem" :show-overflow-tooltip="!item.isNotooltip">
                <template #default="scope">
                  <template v-if="item.render">
                    <hsTableRender :render="item.render(scope)"></hsTableRender>
                  </template>
                  <template v-else>
                    <span :class="{
                      'zs-text-red': percentageKey.includes(headerItem.prop) && (scope.row[headerItem.prop] && scope.row[headerItem.prop+'Color'] == 1), 
                      'zs-text-green': percentageKey.includes(headerItem.prop) && (scope.row[headerItem.prop] && scope.row[headerItem.prop+'Color'] == 3), 
                      }">{{ scope.row[headerItem.prop] ? toThousands(scope.row[headerItem.prop]) + (percentageKey.includes(headerItem.prop) ? '%' : '') : '-' }}</span>
                  </template>
                </template>
              </el-table-column>
            </template>
            <template v-else>
              <span>{{ scope.row[item.prop] ? toThousands(scope.row[item.prop]) : '-' }}</span>
            </template>
          </template>
          </el-table-column>
        </template>
        <template #bottomTip>
          <div v-if="isHaveUnit" class="bottom-box zs-space-top">
            <div class="zs-text-gray-dark zs-text-sm">数据期间：{{ unitVal }}</div>
            <div class="zs-text-gray-dark zs-text-sm">更新时间：{{ updateTime }}</div>
          </div>
        </template>
      </hsPageTable>
      <div v-else style="overflow:auto;height: 100%;">
        <el-scrollbar>
          <div :style="{width:echartsWidth,height:'calc(100% - 30px)'}">
            <BarEchart class="zs-layout-grow zs-overflow-auto" echartId="energyMapMangeBusinessEchartId"
              v-loading="echartsData.loading" :echartData="echartsData.data"></BarEchart>
          </div>
          <div v-if="isHaveUnit" class="bottom-box zs-space-top">
            <div class="zs-text-gray-dark zs-text-sm">数据期间：{{ unitVal }}</div>
            <div class="zs-text-gray-dark zs-text-sm">更新时间：{{ updateTime }}</div>
          </div>
        </el-scrollbar>
      </div>
    </div>
  </div>
</template>

<script setup lang="jsx">
// import PageTable from '@/components/page-table.vue';
// import * as echarts from 'echarts'
import BarEchart from "@/components/EchartComponent/BarEchart";
import { 
  queryBusinessEnergyChartListApi, 
  queryBusinessEnergyMapListApi, 
  exportBusinessEnergyListApi, 
  projectDropDownApi,
  exportBusinessEnergyGraphExportApi
} from "@/api/SpecialReport/index.js"
import dbPublicApi from '@/api/dbPublic'
import { downloadNewFile } from "@/utils/publicUtils"
import { toThousands } from '@/utils/number-util'
import { reactive, ref } from "vue"
import { useRouter } from 'vue-router'
import { useStore } from "vuex";
let store = useStore();
let router = useRouter()
const curPageSize = ref(store.state.uiPageSizeDefault);

const updateDate = ref('')
const getDate = async () => {
  await dbPublicApi.queryDataTimeApi().then((res) => {
    if (res.data.code == 200) {
      updateDate.value = res.data.data
    }
  })
}
getDate()

let projectList = ref([])
function getProjectDropDownFn () {
  projectDropDownApi().then(res => {
    if (res.data.code == 200) {
      projectList.value = res.data.data
    }
  })
}
getProjectDropDownFn()

let curCardDataType = ref('list')

// 数据字典数据
const dictObj = store.getters.getDictObj(['PROJECT_COMMERCIAL_ACTIVITIES', 'INVESTOR'])

// 城市数据
let citys = JSON.parse(localStorage.getItem('addrTree')).list
citys.forEach(el => {
  el.child = el.childList
})
// 城市props
let cascaderProp = {
  children: 'child',
  label: 'name',
  value: 'code',
  emitPath: false,
  // multiple: true 
}

// 查询条件
let queryParams = reactive({
  biProjectCode: '',
  cityId: '',
  formatCode: '',
  groupCode: '',
  yearmonth: '',
  pageNo: 1,
  pageSize: curPageSize
})

let percentageKey = ['accEnergyCostsErlier','accElectricChargeErlier','accWaterRateErlier','accFuelErlier']
// 表格数据
let tableData = reactive({
  loading: false,
  data: [],
  total: 0,
  columns: [
    { prop: 'projectName', align: "left", label: '项目名称', fixed:'left', minWidth:'170', type:'html',
      render: ({ row }) => {
        return <span class="zs-link" onClick={()=>{jumpEnergyCostsPage(row)}}>{row.projectName}</span>
      } 
    },
    { prop: 'formatName', align: "center", label: '业态', width:'70' },
    { prop: 'groupName', align: "center", label: '集团', width:'70' },
    { prop: 'cityName', align: "center", label: '城市', width:'70' },
    { prop: 'projectArea', align: "right", label: '建筑面积',width:'120' },
    { prop: 'EnergyCost', label:'能源费合计', align:'center', headers:[
      { prop: 'accEnergyCosts', align: "right", label: '合计', width:'100' },
      { prop: 'ecAccMonthUnitPrice', align: "right", label: '月均单方', width:'120' },
      { prop: 'accEnergyCostsErlier', align: "right", label: '同比', width:'120' },
    ]},
    { prop: 'ElectricityBill', label:'电费', align:'center', headers:[
      { prop: 'accElectricCharge', align: "right", label: '合计', width:'100' },
      { prop: 'dfAccMonthUnitPrice', align: "right", label: '月均单方', width:'120' },
      { prop: 'accElectricChargeErlier', align: "right", label: '同比', width:'120' },
    ]},
    { prop: 'WaterCost', label:'水费', align:'center', headers:[
      { prop: 'accWaterRate', align: "right", label: '合计', width:'100' },
      { prop: 'sfAccMonthUnitPrice', align: "right", label: '月均单方', width:'120' },
      { prop: 'accWaterRateErlier', align: "right", label: '同比', width:'120' },
    ]},
    { prop: 'FuelCost', label:'燃料费', align:'center', headers:[
      { prop: 'accFuel', align: "right", label: '合计', width:'100' },
      { prop: 'rlfAccMonthUnitPrice', align: "right", label: '月均单方', width:'120' },
      { prop: 'accFuelErlier', align: "right", label: '同比', width:'120' },
    ]},
  ],
  headerCellClassFn:setCellCalss,
  cellClassFn:setCellCalss
})
function setCellCalss({ column }) {
  let arr = ['projectName','cityName','EnergyCost','ElectricityBill','WaterCost','FuelCost','projectArea','accEnergyCostsErlier','accElectricChargeErlier','accWaterRateErlier']
  if (arr.includes(column.property)) {
    return 'zs-table-cell-border-right'
  }
}

function jumpEnergyCostsPage(row) {
  router.push({
    path: '/page/routeController/index',
    query: {
      rid: 'Manage_Business_energyCosts_Detail',
      rTitle: '能耗分析',
      biProjectCode:row.biProjectCode,
      projectName: decodeURI(row.projectName),
      updateDate:updateDate.value,
      tabPermi:'p_btn_901_jingyingxiangmu_shangye',
    },
  })
}

// 获取列表数据
let isHaveUnit = ref(true)
let updateTime = ref('')
let unitVal = ref('')
function getListData () {
  tableData.loading = true
  let params = Object.assign({}, queryParams)
  params.biProjectCode = [params.biProjectCode]
  queryBusinessEnergyMapListApi(params).then(res => {
    let resData = res.data
    if (resData.code == 200) {
      tableData.data = resData.data.childList
      tableData.total = resData.data.totalCount
      if (resData.data.childList[0]) {
        let {dateUpdate, timeLab} = resData.data.childList[0]
        updateTime.value = dateUpdate || ''
        unitVal.value = (timeLab ? timeLab+'； ' : '') + '金额：万元；单方：元/平米/月'
        isHaveUnit.value = true
      } else {
        isHaveUnit.value = false
      }
    }
    tableData.loading = false
  })
}

// 分页变换
function pageChange (page) {
  queryParams.pageNo = page.current
  queryParams.pageSize = page.pageSize
  getListData()
}



// 图表数据
let echartsWidth = ref('100%')
let echartsData = reactive({
  loading: false,
  data: {
    xData:[],
    xLable:[],
    yData:[]
  }
})
// 获取图表数据
function getChartData () {
  echartsData.loading = true
  let params = Object.assign({}, queryParams)
  params.biProjectCode = [params.biProjectCode]
  queryBusinessEnergyChartListApi(params).then(res => {
    let resData = res.data
    if (resData.code == 200) {
      echartsData.data = resData.data
      if (resData.data.yData && resData.data.yData[0].data.length > 20) {
        echartsWidth.value = 60 * resData.data.yData[0].data.length + 'px'
      } else {
        echartsWidth.value = '100%'
      }
    }
    echartsData.loading = false
  })
}


// 统一查询
function queryList () {
  getListData()
  getChartData()
  // if (curCardDataType.value == 'list') {
  // } else {
  // }
}
queryList()

// 点击切换
function handleSwitch (type) {
  curCardDataType.value = type
  // queryList()
}


// 导出
function handleDownload () {
  let params = Object.assign({}, queryParams)
  params.biProjectCode = [params.biProjectCode]
  if (curCardDataType.value == 'list') {
    exportBusinessEnergyListApi(params).then(res => {
        downloadNewFile(res.data, `商业能源地图列表.xls`)
    })
  } else {
    exportBusinessEnergyGraphExportApi(params).then(res => {
        downloadNewFile(res.data, `商业能源地图图表.xls`)
    })
    // let myChart = echarts.init(document.getElementById('energyMapMangeBusinessEchartId'))
    // let img = new Image()
    // img.src = myChart.getDataURL({
    //   type: "png",
    //   pixelRatio: 2,
    //   backgroundColor: "#fff",
    // });
    // img.onload = function () {
    //   var canvas = document.createElement("canvas");
    //   canvas.width = img.width;
    //   canvas.height = img.height;
    //   var ctx = canvas.getContext("2d");
    //   ctx.drawImage(img, 0, 0);
    //   var dataURL = canvas.toDataURL("image/png");
    //   var a = document.createElement("a");
    //   var event = new MouseEvent("click");
    //   a.download = "图片.png" || "下载图片名称";
    //   // 将生成的URL设置为a.href属性
    //   a.href = dataURL;
    //   // 触发a的单击事件
    //   a.dispatchEvent(event);
    //   a.remove();
    // };
  }
}
</script>

<style lang="scss" scoped>
#energyMapMangeBusinessEchartId{
  height: 100%;
}
.el-scrollbar :deep(.el-scrollbar__view) {
  height: 100%;
}
.box{
  width: 100%;
  height: 100%;
}
.bottom-box{
  display: flex;
  justify-content: space-between;
}
.popover-container {
  display: flex;
  flex-wrap: wrap;
}
.cur-picker-container {
  width: 448px;
}
:deep(.el-table--group .el-table__cell){
  border-right: none;
}
:deep(.el-table--border::after), :deep(.el-table--border::before){
  width: 0;
}
:deep(.el-table__border-left-patch){
  background-color: transparent;
}
:deep(.el-table__row .zs-link){
  cursor: pointer !important;
}
:deep(.el-table--group .el-table__inner-wrapper tr:first-child td:first-child){
  border-left: 0;
}
</style>